package com.bwsoft.admin.service.impl;

import com.bwsoft.admin.domain.Account;
import com.bwsoft.admin.domain.Standard;
import com.bwsoft.admin.domain.valueObject.StandardListVO;
import com.bwsoft.admin.domain.valueObject.StandardVO;
import com.bwsoft.admin.service.StandardService;
import com.bwsoft.api.pojo.ResponsePojo;
import com.bwsoft.api.util.Constant;
import com.bwsoft.domain.User;
import com.bwsoft.model.Message;
import com.bwsoft.service.DictionaryDataService;
import com.bwsoft.util.UploadFileUtil;
import com.bwsoft.util.ZipUtil;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.*;
import java.util.Map.Entry;

@Service(StandardService.NAME)
public class StandardServiceImpl extends BaseServiceImpl_ybd implements StandardService {
	private static Logger LOG = Logger.getLogger(StandardService.class.getClass());
	@Resource(name =  DictionaryDataService.NAME)
	DictionaryDataService dictionaryDataService;
	
	
	@Override
	public List<Standard> findData(Integer page, Integer rows, String s_type,
			String s_field, String s_uploader, String s_standardName,
			String s_status, String s_displayStatus) {
		StringBuffer standardHql = new StringBuffer();
		Map<String, String> fieldMap=dictionaryDataService.getDicDataByName("standard_field");
		Map<String, String> typeMap=dictionaryDataService.getDicDataByName("standard_type");
		Map<String, String> statusMap=dictionaryDataService.getDicDataByName("audit_status");
		standardHql.append("from Standard as std where 1=1");
		if(s_type != null && !"".equals(s_type.trim())){
				standardHql.append("and std.type = '"+s_type.trim()+"'");
		}
		if(s_field != null && !"".equals(s_field.trim())){
			standardHql.append("and std.field = '"+s_field.trim()+"'");
		}
		if(s_uploader != null && !"".equals(s_uploader.trim())){
			standardHql.append("and std.uploader.nickName like '%"+s_uploader.trim()+"%'");
		}
		if(s_standardName != null && !"".equals(s_standardName.trim())){
			standardHql.append("and std.standardName like '%"+s_standardName.trim()+"%'");
		}
		if(s_status != null && !"".equals(s_status.trim())){
			standardHql.append("and std.status = '"+s_status.trim()+"'");
		}
		if(s_displayStatus != null && !"".equals(s_displayStatus.trim())){
			standardHql.append("and std.displayStatus = '"+s_displayStatus.trim()+"'");
		}
		standardHql.append(" order by std.addTime desc");
		List<Standard> standardData=standardDao.findPage(standardHql.toString(), rows, (page - 1) * rows);
		for (Standard standard : standardData) {
			standard.setFieldName(fieldMap.containsKey(standard.getField().toString())?fieldMap.get(standard.getField().toString()):"");
			standard.setTypeName(typeMap.containsKey(standard.getType().toString())?typeMap.get(standard.getType().toString()):"" );
			standard.setStatusName(statusMap.containsKey(standard.getStatus().toString())?statusMap.get(standard.getStatus().toString()):"");
		}
		
		return standardData;
	}
	
	@Override
	public long getCount(String s_type,
			String s_field, String s_uploader, String s_standardName,
			String s_status, String s_displayStatus) {
		StringBuffer standardHql = new StringBuffer();
		standardHql.append("select count(*) from Standard as std where 1=1 ");
		if(s_type != null && !"".equals(s_type.trim())){
				standardHql.append(" and std.type = '"+s_type.trim()+"'");
		}
		if(s_field != null && !"".equals(s_field.trim())){
			standardHql.append(" and std.field = '"+s_field.trim()+"'");
		}
		if(s_uploader != null && !"".equals(s_uploader.trim())){
			standardHql.append(" and std.uploader.nickName like '%"+s_uploader.trim()+"%'");
		}
		if(s_standardName != null && !"".equals(s_standardName.trim())){
			standardHql.append(" and std.standardName like '%"+s_standardName.trim()+"%'");
		}
		if(s_status != null && !"".equals(s_status.trim())){
			standardHql.append(" and std.status = '"+s_status.trim()+"'");
		}
		if(s_displayStatus != null && !"".equals(s_displayStatus.trim())){
			standardHql.append(" and std.displayStatus = '"+s_displayStatus.trim()+"'");
		}
		standardHql.append(" order by std.addTime desc");
		return (Long)standardDao.findByHql(standardHql.toString()).get(0);
	}
	
	@Override
	public int getTotalCount(String s_type,
			String s_field, String s_uploader, String s_standardName,
			String s_status, String s_displayStatus) {
		int count=0;
		
		StringBuffer standardHql = new StringBuffer();
		standardHql.append("select count(*) from Standard as std where 1=1 ");
		if(s_type != null && !"".equals(s_type.trim())){
				standardHql.append(" and std.type = '"+s_type.trim()+"'");
		}
		if(s_field != null && !"".equals(s_field.trim())){
			standardHql.append(" and std.field = '"+s_field.trim()+"'");
		}
		if(s_uploader != null && !"".equals(s_uploader.trim())){
			standardHql.append(" and std.uploader.nickName like '%"+s_uploader.trim()+"%'");
		}
		if(s_standardName != null && !"".equals(s_standardName.trim())){
			standardHql.append(" and std.standardName like '%"+s_standardName.trim()+"%'");
		}
		if(s_status != null && !"".equals(s_status.trim())){
			standardHql.append(" and std.status = '"+s_status.trim()+"'");
		}
		if(s_displayStatus != null && !"".equals(s_displayStatus.trim())){
			standardHql.append(" and std.displayStatus = '"+s_displayStatus.trim()+"'");
		}
		count = Integer.valueOf(standardDao.findByHql(standardHql.toString()).get(0).toString());
		return count;
	}

	@Override
	public Message saveOrUpdateStandard(Standard standard,File annex,String annexName) {
		Message msg = new Message();
		com.bwsoft.admin.domain.File filePojo = new com.bwsoft.admin.domain.File();
		try {
			standard.setAddTime(new Date());
			if(standard.getStandardId() != null && !"".equals(standard.getStandardId())){
				Standard updataBefor = standardDao.findById(standard.getStandardId());
				standard.setAddTime(updataBefor.getAddTime());
				standard.setFile(updataBefor.getFile());
				standard.setUploader(updataBefor.getUploader());
				if(standard.getUploader() != null || !"".equals(standard.getUploader())){
					standard.setHtUploader(updataBefor.getHtUploader());
				}
			}
			//---------附件上传（如果没上传则取原数据库内容保存）--------------
			if(annex != null && !"".equals(annex)){
				Calendar now = Calendar.getInstance();
				String annexFilepath = ServletActionContext.getServletContext().getRealPath(Constant.PATH_PDF_STANDARD+"/"+now.get(Calendar.YEAR)+(now.get(Calendar.MONTH) + 1));
				String annexFileName=null ;
				annexFileName=UUID.randomUUID().toString()+annexName.substring(annexName.lastIndexOf('.'), annexName.length());
				UploadFileUtil.uploadOneFile(annexFileName, annex, annexFilepath);
				filePojo.setPath(Constant.PATH_PDF_STANDARD+"/"+now.get(Calendar.YEAR)+(now.get(Calendar.MONTH) + 1)+"/"+annexFileName);
				filePojo.setName(annexName);
				filePojo.setSize(String.valueOf(annex.length()));
				filePojo.setAddTime(new Date());
				standard.setFile(filePojo);
				standard.setStatus(1);
				standard.setLookPower(1);
				standard.setDisplayStatus(false);
			}
			if(standard.getUploader() == null || "".equals(standard.getUploader())){
				standard.setHtscFlag(true);
				standard.setHtUploader((User)ServletActionContext.getRequest().getSession().getAttribute("User"));
			}else{
				standard.setHtscFlag(false);
			}
			standardDao.saveOrUpdate(standard);
			msg.setMsgFlag(true);
			msg.setMsgStr("保存成功！");
		} catch (Exception e) {
			msg.setMsgFlag(false);
			msg.setMsgStr("保存失败：" + e.toString());
			LOG.info(e);
		}
		return msg;
	}

	@Override
	public Standard standardModifyInfo(Integer id) {
		Standard standard=null;
		try{
			standard = standardDao.findById(id);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return standard;
	}

	@Override
	public Message auditPass(String standardIds) {
		Message msg = new Message();
		try {
			StringBuffer standardHql = new StringBuffer();
			standardHql.append("update Standard std set std.status=1 where std.standardId in ("+standardIds+")"); 
			standardDao.executeByHql(standardHql.toString());
			msg.setMsgFlag(true);
			msg.setMsgStr("保存成功！");
		} catch (Exception e) {
			msg.setMsgFlag(false);
			msg.setMsgStr("保存失败：" + e.toString());
			LOG.info(e);
		}
		return msg;
	}

	@Override
	public Message auditNoPass(String standardIds) {
		Message msg = new Message();
		try {
			StringBuffer standardHql = new StringBuffer();
			standardHql.append("update Standard std set std.status=2, std.displayStatus=0 where std.standardId in ("+standardIds+")"); 
			standardDao.executeByHql(standardHql.toString());
			msg.setMsgFlag(true);
			msg.setMsgStr("保存成功！");
		} catch (Exception e) {
			msg.setMsgFlag(false);
			msg.setMsgStr("保存失败：" + e.toString());
			LOG.info(e);
		}
		return msg;
	}

	@Override
	public Message show(String standardIds) {
		Message msg = new Message();
		try {
			StringBuffer standardHql = new StringBuffer();
			standardHql.append("update Standard std set std.displayStatus=1 where std.standardId in ("+standardIds+")"); 
			standardDao.executeByHql(standardHql.toString());
			msg.setMsgFlag(true);
			msg.setMsgStr("保存成功！");
		} catch (Exception e) {
			msg.setMsgFlag(false);
			msg.setMsgStr("保存失败：" + e.toString());
			LOG.info(e);
		}
		return msg;
	}

	@Override
	public Message hide(String standardIds) {
		Message msg = new Message();
		try {
			StringBuffer standardHql = new StringBuffer();
			standardHql.append("update Standard std set std.displayStatus=0 where std.standardId in ("+standardIds+")"); 
			standardDao.executeByHql(standardHql.toString());
			msg.setMsgFlag(true);
			msg.setMsgStr("保存成功！");
		} catch (Exception e) {
			msg.setMsgFlag(false);
			msg.setMsgStr("保存失败：" + e.toString());
			LOG.info(e);
		}
		return msg;
	}

	@Override
	public Message saveBatch(Standard standard,File annex,String annexName) {
		request = ServletActionContext.getRequest();
		Message msg = new Message();
		com.bwsoft.admin.domain.File filePojo = new com.bwsoft.admin.domain.File();
		try {
			if(annex != null && !"".equals(annex)){
				Calendar now = Calendar.getInstance();
				String today = String.valueOf(now.get(Calendar.YEAR))+String.valueOf((now.get(Calendar.MONTH) + 1))+String.valueOf(now.get(Calendar.DAY_OF_MONTH))+String.valueOf(now.get(Calendar.HOUR_OF_DAY))
						+String.valueOf(now.get(Calendar.MINUTE))+String.valueOf(now.get(Calendar.SECOND))+annexName.substring(0,annexName.lastIndexOf("."));
				String annexFilepath = ServletActionContext.getServletContext().getRealPath(Constant.PATH_RARTEMP);
				String annexFileName=null ;
				annexFileName=annexName;
				UploadFileUtil.uploadOneFile(annexFileName, annex, annexFilepath);
//				压缩包解压到上传标准附件的文件夹中
				ZipUtil zu=new ZipUtil();
				String zipPath=request.getSession().getServletContext().getRealPath(Constant.PATH_RARTEMP+"/"+annexFileName);
				String standardPath=request.getSession().getServletContext().getRealPath(Constant.PATH_PDF_STANDARD+"/"+ today);
				System.out.println(zipPath);
				System.out.println(standardPath);
				Map<String, Long> map = zu.readByApacheZipFile(zipPath, standardPath);
//				存储文件中的标准附件
				Set<Entry<String, Long>>  entries = map.entrySet( );
				if(entries != null) {
					Iterator iterator = entries.iterator( );
					while(iterator.hasNext( )) {
						filePojo = new com.bwsoft.admin.domain.File();
						
						Map.Entry entry =(Entry) iterator.next( );
						String key = String.valueOf(entry.getKey()).replaceAll("'", "''");
						String value = String.valueOf(entry.getValue());
						filePojo.setPath(Constant.PATH_PDF_STANDARD+"/"+ today +"/"+key);
						filePojo.setName(key);
						filePojo.setSize(value);
						filePojo.setAddTime(new Date());
						
						StringBuffer standardHql = new StringBuffer();
						standardHql.append("from Standard as std where 1=1");
						standardHql.append(" and std.standardName = '"+ key +"'");
						standardHql.append(" and std.field = "+ standard.getField());
						standardHql.append(" and std.type = "+ standard.getType());
						List<Standard> isAlready = standardDao.findByHql(standardHql.toString());
						if(isAlready.size() > 0){
							isAlready.get(0).setFile(filePojo);
							standardDao.update(isAlready.get(0));
							continue;
						}
						standard.setFile(filePojo);
						standard.setStatus(1);
						standard.setLookPower(1);
						standard.setDisplayStatus(true);
						standard.setHtscFlag(true);
						standard.setHtUploader((User)ServletActionContext.getRequest().getSession().getAttribute("User"));
						standard.setAddTime(new Date());
						if(key.lastIndexOf(".pdf") >= 0){
							standard.setStandardName(key.substring(0, key.lastIndexOf(".pdf")));
						}else if(key.lastIndexOf(".PDF") >= 0){
							standard.setStandardName(key.substring(0, key.lastIndexOf(".PDF")));
						}else{
							standard.setStandardName(key);
						}
//						standardDao.saveOrUpdate(standard);
						standardDao.save(standard);
					}
				}
				msg.setMsgFlag(true);
				msg.setMsgStr("保存成功！");
				File file = new File(zipPath); 
				clearDir(file);
			}
		} catch (Exception e) {
			msg.setMsgFlag(false);
			msg.setMsgStr("保存失败：" + e.toString());
			e.printStackTrace();
			LOG.info(e);
		}
		return msg;
	}

	
    @Override
	public Message remove(String standardIds) {
    	Message msg = new Message();
		try {
			StringBuffer standardHql = new StringBuffer();
			standardHql.append("delete from Standard std where std.standardId in ("+standardIds+")"); 
			standardDao.executeByHql(standardHql.toString());
			msg.setMsgFlag(true);
			msg.setMsgStr("删除成功！");
		} catch (Exception e) {
			msg.setMsgFlag(false);
			msg.setMsgStr("删除失败：" + e.toString());
			LOG.info(e);
		}
		return msg;
	}

	/**
     *  根据路径删除指定的目录或文件，无论存在与否
     *@param file  要删除的目录或文件
     *@return 删除成功返回 true，否则返回 false。
     */
	public static void clearDir(File file) {
		if (file.isFile() && file.exists()) {
	        if (file.isDirectory()) {
	            for (File f : file.listFiles()) {
	                clearDir(f);
	                f.delete();
	            }
	        }
	        file.delete();
		}
    }

	@Override
	public List<StandardVO> getVo(List<Standard> standards) {
		List<StandardVO> standardListVo = new ArrayList<StandardVO>();
		StandardVO standardVo = new StandardVO();
		for (Standard standard : standards) {
			standardVo = new StandardVO();
			standardVo.setAddTime(standard.getAddTime());
			standardVo.setStandardId(standard.getStandardId());
			standardVo.setDisplayStatus(standard.getDisplayStatus());
			standardVo.setFieldName(standard.getFieldName());
			if(standard.getFile() != null && !"".equals(standard.getFile())){
				standardVo.setFileId(standard.getFile().getId().toString());
				standardVo.setFileName(standard.getFile().getName());
				standardVo.setFilePath(standard.getFile().getPath());
				standardVo.setFileSize(standard.getFile().getSize());
			}
			standardVo.setHtscFlag(standard.getHtscFlag());
			if(standard.getHtUploader() != null && !"".equals(standard.getHtUploader())){
				standardVo.setHtUploaderName(standard.getHtUploader().getName());
			}
			standardVo.setStandardName(standard.getStandardName());
			standardVo.setStatusName(standard.getStatusName());
			standardVo.setTypeName(standard.getTypeName());
			if(standard.getUploader() != null && !"".equals(standard.getUploader())){
				standardVo.setUploaderEmail(standard.getUploader().getEmail());
				standardVo.setUploaderFax(standard.getUploader().getFax());
				standardVo.setUploaderId(standard.getUploader().getAccountId());
				standardVo.setUploaderLinkMan(standard.getUploader().getLinkMan());
				standardVo.setUploaderNickName(standard.getUploader().getNickName());
				standardVo.setUploaderPhone(standard.getUploader().getPhone());
			}
			
			standardVo.setType(standard.getType());
			standardVo.setField(standard.getField());
			standardVo.setStatus(standard.getStatus());
			standardVo.setLookPower(standard.getLookPower());
			
			standardListVo.add(standardVo);
		}
		return standardListVo;
	}

	@Override
	public List<StandardListVO> getListVo(List<Standard> standards) {
		List<StandardListVO> standardListVo = new ArrayList<StandardListVO>();
		StandardListVO standardVo = new StandardListVO();
		for (Standard standard : standards) {
			standardVo = new StandardListVO();
			standardVo.setAddTime(standard.getAddTime());
			standardVo.setStandardId(standard.getStandardId());
			standardVo.setStandardName(standard.getStandardName());
			standardListVo.add(standardVo);
		}
		return standardListVo;
	}

	@Override
	public ResponsePojo saveOrUpdateStandard(String standardName, Account account,
			String field, String type, File stdfile, String stdfileName) {
		Standard standard = new Standard();
		ResponsePojo rp = new ResponsePojo();
		com.bwsoft.admin.domain.File filePojo = new com.bwsoft.admin.domain.File();
		try {
			standard.setAddTime(new Date());
			//---------附件上传（如果没上传则取原数据库内容保存）--------------
			if(stdfile != null && !"".equals(stdfile)){
				Calendar now = Calendar.getInstance();
				String stdFilepath = ServletActionContext.getServletContext().getRealPath(Constant.PATH_PDF_STANDARD+"/"+now.get(Calendar.YEAR)+(now.get(Calendar.MONTH) + 1));
				String newFileName=null ;
				newFileName=UUID.randomUUID().toString()+stdfileName.substring(stdfileName.lastIndexOf('.'), stdfileName.length());
				UploadFileUtil.uploadOneFile(newFileName, stdfile, stdFilepath);
				filePojo.setPath(Constant.PATH_PDF_STANDARD+"/"+now.get(Calendar.YEAR)+(now.get(Calendar.MONTH) + 1)+"/"+newFileName);
				filePojo.setName(stdfileName);
				filePojo.setSize(String.valueOf(stdfile.length()));
				filePojo.setAddTime(new Date());
				standard.setFile(filePojo);
			}
			standard.setUploader(account);
			standard.setField(Integer.valueOf(field));
			standard.setType(Integer.valueOf(type));
			standard.setStatus(0);
			standard.setDisplayStatus(false);
			standard.setHtscFlag(false);
			standard.setStandardName(standardName);
			standard.setHtUploader((User)ServletActionContext.getRequest().getSession().getAttribute("User"));
			standardDao.saveOrUpdate(standard);
			rp.setErrcode(0);
			rp.setErrmsg("保存成功！");
		} catch (Exception e) {
			rp.setErrcode(5);
			rp.setErrmsg("保存失败：" + e.toString());
			LOG.info(e);
		}
		return rp;
	}
	
	//2016.08.14新加功能 未登录时显示和隐藏
	@Override
	public Message noLoginShow(String standardIds) {
		Message msg = new Message();
		try {
			StringBuffer standardHql = new StringBuffer();
			standardHql.append("update Standard std set std.lookPower=1 where std.standardId in ("+standardIds+")"); 
			standardDao.executeByHql(standardHql.toString());
			msg.setMsgFlag(true);
			msg.setMsgStr("保存成功！");
		} catch (Exception e) {
			msg.setMsgFlag(false);
			msg.setMsgStr("保存失败：" + e.toString());
			LOG.info(e);
		}
		return msg;
	}

	@Override
	public Message noLoginHide(String standardIds) {
		Message msg = new Message();
		try {
			StringBuffer standardHql = new StringBuffer();
			standardHql.append("update Standard std set std.lookPower=0 where std.standardId in ("+standardIds+")"); 
			standardDao.executeByHql(standardHql.toString());
			msg.setMsgFlag(true);
			msg.setMsgStr("保存成功！");
		} catch (Exception e) {
			msg.setMsgFlag(false);
			msg.setMsgStr("保存失败：" + e.toString());
			LOG.info(e);
		}
		return msg;
	}
	
	
}
